<script setup>
import {onMounted, reactive, ref, toRefs} from "vue";
import {userDelete, userDetail, userList} from "../../api/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import Add from "./Add.vue";

const data = reactive({
  tableData: [],
  loading: false,
  currentData: {}
})

const infoVisible = ref(false)
const updateFlag = ref(false)

const getUserList = () => {
  data.loading = true;
  userList({}).then(response => {
    data.tableData = response.data.data
    data.loading = false
  }).catch(error => {
    console.log(error)
    data.loading = false
  })
}

const deleteUser = (row) => {
  ElMessageBox.confirm(
      '确认删除用户:' + row.username,
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    data.loading = true;
    userDelete(row.id).then(response => {
      ElMessage.success(response.data.message)
      data.loading = false
      getUserList()
    })
  }).catch(() => {

  })
}

const updateUser = (row) => {
  updateFlag.value = true
  data.loading = true;
  userDetail(row.id).then(response => {
    data.currentData = response.data.data
    infoVisible.value = true
    data.loading = false
  })
}

//打开添加用户弹窗
const toAddUser = () => {
  updateFlag.value = false
  infoVisible.value = true
}

const addUserClose = () => {
  infoVisible.value = false
  data.currentData = {}
  getUserList()
}

onMounted(() => {
  getUserList()
})

const {tableData, loading, currentData} = toRefs(data)
</script>

<template>
  <el-card v-loading="loading" element-loading-text="加载中，请稍后...">
    <template #header>
      <div class="card-header">
        <span>用户列表</span>
        <div>
          <el-button @click="getUserList">查询</el-button>
          <el-button @click="toAddUser">添加用户</el-button>
        </div>
      </div>
    </template>
    <el-table :data="tableData" style="width: 100%" height="600" border>
      <el-table-column fixed sortable prop="username" label="用户名" width="180"/>
      <el-table-column sortable prop="id" label="ID" width="180"/>
      <el-table-column prop="qq" label="QQ号" width="180"/>
      <el-table-column prop="address" label="Address"/>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small">
            详情
          </el-button>
          <el-button link type="primary" size="small" @click="updateUser(scope.row)">修改</el-button>
          <el-button link type="warning" size="small" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-dialog v-model="infoVisible" :title="updateFlag ? '修改用户':'添加用户'" width="600" center :close-on-click-modal="false" destroy-on-close>
    <Add @close="addUserClose" :load-data="currentData" :is-update="updateFlag"/>
  </el-dialog>

</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
}
</style>